//
//  WmcHomeVM+VideoTimer.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/7/7.
//

import UIKit
import YPBedrock
import AVFoundation

public extension WmcHomeVM {
    /// 录制视频中断原因
    enum BreakOffType {
        /// 无，用户操作正常中断
        case none
        /// 来电
        case phoneCall
        /// app返回后台
        case appEnterBackground
        /// 视频到时长上限
        case timeOut
        /// 未知
        case unknown
    }

    enum VideoTimeOutTipsType {
        case toast
        case alert
    }
}

extension WmcHomeVM {
    /// 保存视频
    func saveVideo(url: URL, watermarkModel: WmcWatermarkDetailModel, breakOffType: WmcHomeVM.BreakOffType) {
        // 保存和上传视频
        saveAndUpload(videoUrl: url, watermarkModel: watermarkModel, breakOffType: breakOffType) { saveUrl in
            // 存入系统相册
            WmcAlbumManager.saveMyAlbumCollection(videoUrl: saveUrl) { [weak self] in
                // 存入完成回调
                guard let weakSelf = self else { return }
                weakSelf.newUserTakeVideoAlert()
            }
        }
    }

    /// 保存和上传视频
    func saveAndUpload(videoUrl: URL, watermarkModel: WmcWatermarkDetailModel, breakOffType: WmcHomeVM.BreakOffType, resultBlock: @escaping YPBlock.OneParam<URL>) {
        // 生成水印信息
        let watermarkInfoDic: [String: Any] = watermarkModel.toJSON() ?? [:]
        let watermarkInfo = WmcWatermarkDataTool.createWatermark(watermarkInfoDic, addressModel: WmcLocationManager.shared.poiStatus.value?.data, addressPrefix: WmcLocationManager.shared.addressPrefix)

        // 提交统计数据
        let watermarkType = watermarkModel.wmId.yp.string

        // 获取当前活动id
        var activity: YPWmcManager.ActivityType?
        let activityList = YPWmcManager.shared.delegate.activityDelegate?.openActivityType(.current)
        if activityList?.contains(.yp_giveIntegral) == true {
            activity = .yp_giveIntegral
        }

        let videoTime = AVAsset(url: videoUrl).duration.seconds

        WmcPhotoAPI.submitWatermarkInfo(watermarkType: watermarkType, type: 2, watermarkInfo: watermarkInfo.json, videoTime: videoTime, activity: activity?.info.activityValue, success: { [weak self] response in
            guard let weakSelf = self else { return }
//            weakSelf.business_punchCardDayNumRelay.accept(3)
            // 送积分业务线打卡天数
            if let dic = response.data as? [String: Any],
               let punchCardDayNum = dic["take_num"] as? Int {
                // 更新资格,再走一遍资格
                weakSelf.yupao_integral()
                // 回调
                weakSelf.business_punchCardDayNumRelay.accept(punchCardDayNum)
            }
        })

        WmcLocalMediaAlbumDBManager.insertVideo(.init(url: videoUrl),
                                                watermarkJson: watermarkInfo.json)
        { [weak self] mediaType, previewImagePath, previewImageRelativePath, mediaInfoModel in
            guard let weakSelf = self else { return }
            guard let previewImagePath = previewImagePath,
                  let coverImage = UIImage(contentsOfFile: previewImagePath) else { return }

            let videoResult: YPWmcManager.VideoResult = (mediaInfoModel.path.yp.url,
                                                         mediaInfoModel.path,
                                                         coverImage,
                                                         previewImagePath,
                                                         videoTime,
                                                         watermarkModel)

            // 外部事务回调
            watermarkModel.createLocationInfo()
            weakSelf.homeDelegate?.videoRecordComplete(.current,
                                                       videoResult: videoResult,
                                                       breakOffType: breakOffType)

            var defaultAction: WmcActionType = .default
            if let action = weakSelf.homeDelegate?.videoRecordCompleteTimeOutTipsAction(.current,
                                                                                        watermarkModel: watermarkModel,
                                                                                        tipsType: .alert)
            {
                defaultAction = action
            }

            // 询问是否上传
            var isUpload = true
            if let _isUpload = YPWmcManager.shared.delegate.infoDelegate?.videoIsUploadCloudAlbum(.current,
                                                                                                  videoResult: videoResult)
            {
                isUpload = _isUpload
            }

            defaultAction.transactionDefaultCase { [weak self] in // 执行默认Case
                guard let weakSelf = self else { return }
                weakSelf.isLoginWithNewUser { [weak self] isLogin in
                    guard let weakSelf = self else { return }
                    if isLogin {
                        WmcPreferenceSettingsManager.querySyncSwitchConfig { r in
                            if !r.isOpen {
                                return
                            }

                            if videoTime > 60 {
                                let alert = WmcAlertView()
                                alert.title = "提示"
                                alert.contentLabel.textColor = .wmc_grayH2_323233
                                alert.msg = "视频超过60秒，需手动同步至相册，取消后可点击【本地相册】重新手动同步"
                                alert.style = .custom(confirmTitle: "立即同步", cancelTitle: "取消")
                                alert.confirmBlock = { [weak self] in
                                    guard let weakSelf = self else { return }
                                    guard isUpload else { return }
                                    weakSelf.uploadVideo(videoPath: mediaInfoModel.relativePath,
                                                         previewImagePath: previewImageRelativePath,
                                                         videoTime: videoTime,
                                                         watermarkModel: watermarkModel,
                                                         breakOffType: breakOffType)
                                }
                                alert.show()
                            } else {
                                guard isUpload else { return }
                                weakSelf.uploadVideo(videoPath: mediaInfoModel.relativePath,
                                                     previewImagePath: previewImageRelativePath,
                                                     videoTime: videoTime,
                                                     watermarkModel: watermarkModel,
                                                     breakOffType: breakOffType)
                            }
                        } failure: { error in
                            WmcHudManager.toast(error)
                        }
                    }
                }
            }

            resultBlock(mediaInfoModel.path.yp.fileUrl)

            weakSelf.syncLocalAlbumList() // 同步下数据库
        }
    }

    func uploadVideo(videoPath: String,
                     previewImagePath: String,
                     videoTime: Double,
                     watermarkModel: WmcWatermarkDetailModel,
                     breakOffType: WmcHomeVM.BreakOffType) {
        if breakOffType == .phoneCall,
           breakOffType == .appEnterBackground {
            return
        }
        let watermarkInfoDic: [String: Any] = watermarkModel.toJSON() ?? [:]
        let watermarkInfo = WmcWatermarkDataTool.createWatermark(watermarkInfoDic,
                                                                 addressModel: WmcLocationManager.shared.poiStatus.value?.data,
                                                                 addressPrefix: WmcLocationManager.shared.addressPrefix)

        let uploadParams = WmcMediaUploadResourceParameterModel()
        uploadParams.appId = 101 // 锁死水印相机appid
        uploadParams.entryId = 1
        uploadParams.type = 1
        uploadParams.format = "mp4"
        uploadParams.wmcInfo = watermarkInfo.dict
        if let uid = WmcLoginManager.shared.yupaoAccountModel?.userId {
            uploadParams.uid = Int(uid)
        }
        uploadParams.wmId = watermarkModel.wmId

        var date = Date()
        if let networkDate = WmcDateManager.shared.networkDate.value {
            let timeInterval = networkDate.timeIntervalSince1970 - 8 * 60 * 60
            date = Date(timeIntervalSince1970: timeInterval)
        }
        uploadParams.takeTime = date.yp.string(.ymd_hms_iso8601, identifier: .asia(.Shanghai))
        uploadParams.previewImagePath = previewImagePath
        uploadParams.videoTime = Int(videoTime)

        if let poi = WmcLocationManager.shared.poiStatus.value?.data?.poi, let addressPrefix = WmcLocationManager.shared.addressPrefix {
            uploadParams.city = poi.city
            if let poiName = poi.name {
                uploadParams.address = "\(addressPrefix)\(poiName)"
            }
        }
        WmcUploadQueueManager.appendUploadTask(path: videoPath, model: uploadParams)
    }

    // MARK: 计时器方法

    func startRecordingTimer() {
        isShowRecordingTenSecondToast = false
        stopRecordingTimer() // 先停止
        // 开启定时器
        videoRecordTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {
            [weak self] _ in
            guard let self = self else { return }
            self.updateRecordingTimer()
        })
        // 询问外部，获取最大时长
        if let minutes = homeDelegate?.videoRecordMaxMinutes(.current,
                                                             watermarkModel: watermarkRelay.value) {
            recordingMaxTenSeconds = Int(minutes * 60)
        }
    }

    /// 更新计时器
    func updateRecordingTimer() {
        guard videoRecordState == .being else { return }
        // 录制时间+1s
        recordingBeginTenSeconds += 1
        
        let allSeconds = recordingBeginTenSeconds
        // 计算进度
        let progress = allSeconds.yp.cgFloat / recordingMaxTenSeconds.yp.cgFloat
        videoRecordingProgressRelay.accept(progress) // 回调进度
        // 计算已录制时间
        let showSecond = allSeconds % 60
        let timeStr = allSeconds.wmc_secondsToTime
//        print("录制时间==>\(allSeconds)")
        WmcLogManager.Log("视频录制时间：[\(timeStr)]")
        videoRecordingTimeRelay.accept(timeStr) // 回调已录制时间
        // 对外部回调录制时间
        homeDelegate?.videoRecordTimeChange(.current,
                                            watermarkModel: watermarkRelay.value,
                                            seconds: allSeconds)
        // 判断50s弹10s弹窗
        if showSecond >= 50,
           !isShowRecordingTenSecondToast { // 没显示过
            var defaultAction: WmcActionType = .default
            if let action = homeDelegate?.videoRecordCompleteTimeOutTipsAction(.current,
                                                                               watermarkModel: watermarkRelay.value,
                                                                               tipsType: .toast) {
                defaultAction = action
            }
            defaultAction.transactionDefaultCase { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.videoRecordingTipsTostRelay.accept(())
                weakSelf.isShowRecordingTenSecondToast = true
            }
        }
        // 时长上限
        if allSeconds >= recordingMaxTenSeconds { // 抵达时长
            videoStopRecordingRelay.accept(()) // 回调停止录制
        }
    }

    /// 停止计时器
    func stopRecordingTimer() {
        // 清除定时器
        videoRecordTimer?.invalidate()
        videoRecordTimer = nil
        
        recordingBeginTenSeconds = 0 // 清空时长
        videoRecordingProgressRelay.accept(0) // 回调进度
        videoRecordingTimeRelay.accept("00:00") // 回调已录制时间
    }
}
